package com.example.rizhaoscienceandtechnologymuseum.Server;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.baselibrary.Utils.LogUtil;
import com.example.baselibrary.Utils.SelfToastUtil;
import com.example.rizhaoscienceandtechnologymuseum.Utils.TimeUtil;
import com.telpo.tps550.api.TelpoException;
import com.telpo.tps550.api.idcard.CountryMap;
import com.telpo.tps550.api.idcard.IdCard;
import com.telpo.tps550.api.idcard.IdentityMsg;
import com.telpo.tps550.api.util.ReaderUtils;
import com.telpo.tps550.api.util.StringUtil;
import com.telpo.tps550.api.util.SystemUtil;

import java.util.List;

public class IDSearchService extends Service {

    private GetIDInfoTask mAsyncTask;
    private boolean isSerialOpen = false;
    private boolean finishSign = false;
    IdCard idCard;
    private IdentityMsg info;

    Bitmap bitmap;
    byte[] image;
    byte[] fringerprint;
    private String fringerprintData;

    private static IdInfo idInfo;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 1:
                    mAsyncTask = new GetIDInfoTask();
                    mAsyncTask.execute();
                    break;
            }
        }
    };

    public IDSearchService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //服务启动就启动，只会跟随服务启动一次
//        try {
//            IdCard.open(IDSearchService.this);
//        } catch (TelpoException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        idCard = new IdCard(IDSearchService.this);
        if (SystemUtil.getDeviceType() == StringUtil.DeviceModelEnum.TPS350.ordinal()) {
            if (checkPackage("com.example.idcard.hid")) {
                switchToTPS350AUsbIdCard();
            } else {
                SelfToastUtil.getInstance().show("找不到apk");
            }
        } else {
            handler.sendMessageDelayed(handler.obtainMessage(1, ""), 0);
        }


    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private class GetIDInfoTask extends AsyncTask<Void, Integer, TelpoException>{

        @Override
        protected TelpoException doInBackground(Void... voids) {
            if(SystemUtil.getDeviceType() == StringUtil.DeviceModelEnum.TPS900.ordinal()) {
                return new TelpoException();
            }
            TelpoException result = null;
            try {
                if(!isSerialOpen || finishSign) {
                    isSerialOpen = true;
                }
                info = idCard.checkIdCardOverseas(3000);
                if (info!=null) {
                    if ("".equals(info.getName())) {
                        return new TelpoException();
                    }
				/*image = IdCard.getIdCardImage();
				bitmap = IdCard.decodeIdCardImage(image);*/
                    image = idCard.getIdCardImageOverseas(info);
                    bitmap = idCard.decodeIdCardImageOverseas(image);
                    if (!"I".equals(info.getCard_type())) {
                        fringerprint = idCard.getFringerPrintOverseas(info);
                        fringerprintData = ReaderUtils.get_finger_info(IDSearchService.this, fringerprint);
                    }
                }
            } catch (TelpoException e) {
                e.printStackTrace();
                result = e;
            } finally {
                //IdCard.close();
            }


            return result;
        }

        @Override
        protected void onPostExecute(TelpoException result) {
            super.onPostExecute(result);
            if (result == null) {
                if (info != null) {
                    if (info.getName() != null) {
                        idInfo.IdInfo(bitmap,info);
                        LogUtil.d(TimeUtil.getLocationTime());
                    }
                }
            }
            handler.sendEmptyMessageDelayed(1, 500);
        }
    }

    private boolean checkPackage(String packageName) {
        PackageManager manager = this.getPackageManager();
        Intent intent = new Intent().setPackage(packageName);
         @SuppressLint("WrongConstant") List<ResolveInfo> infos = manager.queryIntentActivities(intent, PackageManager.GET_INTENT_FILTERS);
        if (infos == null || infos.size() < 1) {
            return false;
        }
        return true;
    }

    private void switchToTPS350AUsbIdCard() {
        Intent intent = new Intent();
        intent.setClassName("com.example.idcard.hid", "com.example.demo.MiniIDReaderActivityNew");
        startActivity(intent);
    }

    // 写一个接口回调，将数据回调出去
    public interface IdInfo{
        void IdInfo(Bitmap bitmap,IdentityMsg info);
    }

    public static void setIDInfoListener(IdInfo idInfoListener){
        idInfo = idInfoListener;
    }

}
